const router = require('koa-router')();
const utils = require('../utils');

// Schema
const MemorySchema = require('../schema/MemorySchema');
const ErrorSchema = require('../schema/ErrorSchema');
const StaticErrorSchema = require('../schema/StaticErrorSchema');
const StaticInfoSchema = require('../schema/StaticInfoSchema');
const XHRSchema = require('../schema/XHRSchema');
router.prefix('/data')

router.get('/memory', async (ctx, next) => {
    await MemorySchema.find({}).sort({ 'createTime': -1 }).limit(1)
        .then(res => {
            ctx.body = {
                code: 0,
                type: 'memory',
                data: res
            }
        })
        .catch(e => {
            ctx.body = {
                code: 1,
                message: 'failed'
            }
        })
})

router.get('/static/info', async (ctx, next) => {
    let temp = null;
    await StaticInfoSchema.find({}).sort({ batch: -1 }).then(res => {
        console.log(res)
        if(!res[0]) {
            ctx.body = {
                code: 0,
                type: "staticInfo",
                data: []
            }
            return;
        }else {
            temp = res[0];
        }
    }).catch(e => {
        ctx.body = {
            code: -1,
            message: 'failed'
        }
    })

    await StaticInfoSchema.find({batch: temp.batch})
        .then(res => {
            ctx.body = {
                code: 0,
                type: "staticInfo",
                data: res
            }
        })
})

router.get('/static/error', async (ctx, next) => {
    await StaticErrorSchema.find({})
        .then(res => {
            ctx.body = {
                code: 0,
                type: 'staticError',
                data: res
            }
        })
        .catch(e => {
            ctx.body = {
                code: 1,
                message: 'failed'
            }
        })
})
router.get('/error', async (ctx, next) => {
    await ErrorSchema.find({})
        .then(res => {
            ctx.body = {
                code: 0,
                type: 'error',
                data: res
            }
        })
        .catch(e => {
            ctx.body = {
                code: 1,
                message: 'failed'
            }
        })
})
router.get('/xhr', async (ctx, next) => {
    await XHRSchema.find({})
        .then(res => {
            ctx.body = {
                code: 0,
                type: 'xhr',
                data: res
            }
        })
        .catch(e => {
            ctx.body = {
                code: 1,
                message: 'failed'
            }
        })
})
module.exports = router
